<template>
  <div id="sceniclist" class="scenic-list-container">
    <!-- 页面头部 -->
    <div class="header-section">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">
            <i class="el-icon-map-location"></i> 景区信息管理
          </h2>
          <p class="page-subtitle">管理景区相关信息</p>
        </div>
        <div class="total-count">
          <div class="count-card">
            <span class="count-label">景区总数</span>
            <span class="count-value">{{ tableData.length }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <el-card class="query-card">
      <el-form :inline="true" :model="queryForm" class="query-form">
        <el-form-item label="景区名称">
          <el-input v-model="queryForm.scenicAreaName" placeholder="请输入景区名称" clearable />
        </el-form-item>
        <el-form-item label="省份">
          <el-input v-model="queryForm.province" placeholder="请输入省份" clearable />
        </el-form-item>
        <el-form-item label="城市">
          <el-input v-model="queryForm.city" placeholder="请输入城市" clearable />
        </el-form-item>
        <el-form-item>
          <el-button class="primary-btn" type="primary" @click="handleQuery">查询</el-button>
          <el-button class="reset-btn" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div style="display: flex; justify-content: flex-end; gap: 12px; margin-top: 12px;">
        <el-button class="add-btn" @click="handleAdd">添加</el-button>
        <el-button class="danger-btn" type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除</el-button>
      </div>
    </el-card>

    <el-card class="table-card">
      <div class="data-table-card">
        <el-table 
          :data="pagedTableData" 
          border 
          stripe 
          style="width: 100%; margin-top: 10px;"
          @selection-change="handleSelectionChange"
          empty-text="暂无景区数据"
          :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="scenicAreaName" label="景区名称" width="180" align="center" />
          <el-table-column prop="province" label="省份" width="120" align="center" />
          <el-table-column prop="city" label="城市" width="120" align="center" />
          <el-table-column prop="scenicSpotLevel" label="景点级别" width="100" align="center" />
          <el-table-column prop="altitude" label="海拔" width="100" align="center" />
          <el-table-column prop="comprehensiveDifficultyIndex" label="综合难度" width="120" align="center" />
          <el-table-column prop="detailAddress" label="详细地址" width="200" align="center" />
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template #default="scope">
              <el-button class="primary-btn" size="small" type="primary" @click="handleEdit(scope.row.scenicSpotId)">编辑</el-button>
              <el-button class="danger-btn" size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          :page-sizes="[10, 20, 50]"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  data() {
    return {
      tableData: [],
      filteredData: [],
      multipleSelection: [],
      queryForm: {
        scenicAreaName: '',
        province: '',
        city: ''
      },
      regionMap: {}, // regionId -> { province, city }
      pageSize: 10,
      currentPage: 1
    }
  },
  computed: {
    pagedTableData() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredData.slice(start, end)
    }
  },

  methods: {
  fetchRegions() {
  return axios.get('http://localhost:8080/api/regions').then(res => {
    this.regionMap = {}
    res.data.forEach(region => {
      this.regionMap[String(region.regionID)] = {
        province: region.province,
        city: region.city
      }
    })
    console.log('regionMap:', this.regionMap)
  })
},

fetchScenicList() {
  axios.get('http://localhost:8080/mw/ScenicSpotList')
    .then(response => {
      console.log('scenic data:', response.data)
      this.tableData = (response.data || []).map(item => {
        const region = this.regionMap[String(item.regionId)] || {}
        if (!region.province) {
          console.warn('未匹配到地区', item.regionId, this.regionMap)
        }
        return {
          ...item,
          province: region.province || '',
          city: region.city || ''
        }
      })
      this.filteredData = [...this.tableData]
    })
    .catch(error => {
      console.error('获取景区列表失败', error)
      ElMessage.error('获取景区列表失败')
    })
},

    // 查询处理
    handleQuery() {
      this.filteredData = this.tableData.filter(item => {
        const matchesName = this.queryForm.scenicAreaName 
          ? (item.scenicAreaName || '').includes(this.queryForm.scenicAreaName)
          : true
        const matchesProvince = this.queryForm.province
          ? (item.province || '').includes(this.queryForm.province)
          : true
        const matchesCity = this.queryForm.city
          ? (item.city || '').includes(this.queryForm.city)
          : true
        return matchesName && matchesProvince && matchesCity
      })
      this.currentPage = 1
    },

    // 重置查询
    resetQuery() {
      this.queryForm = {
        scenicAreaName: '',
        province: '',
        city: ''
      }
      this.filteredData = [...this.tableData]
      this.currentPage = 1
    },

    // 添加景区（跳转到编辑页面）
    handleAdd() {
      this.$router.push({
        path: '/scenic/edit'
        // 不传 id，ScenicEdit.vue 里 isEdit 会为 false，走新增逻辑
      })
    },

    // 编辑景区
    handleEdit(id) {
      this.$router.push({
        path: '/scenic/edit',
        query: { id }
      })
    },

    // 单个删除
    handleDelete(row) {
      ElMessageBox.confirm(
        `确定要删除景区"${row.scenicAreaName}"吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        axios.delete(`http://localhost:8080/mw/deleteScenicSpotById?id=${row.scenicSpotId}`)
          .then(() => {
            ElMessage.success('删除成功')
            this.fetchScenicList()
          })
          .catch(() => {
            ElMessage.error('删除失败')
          })
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    },

    // 批量删除
    handleBatchDelete() {
      const scenicNames = this.multipleSelection.map(item => item.scenicAreaName).join('、')
      ElMessageBox.confirm(
        `确定要删除选中的${this.multipleSelection.length}个景区吗?<br>${scenicNames}`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      ).then(() => {
        const deletePromises = this.multipleSelection.map(item => 
          axios.delete(`http://localhost:8080/mw/deleteScenicSpotById?id=${item.scenicSpotId}`)
        )
        Promise.all(deletePromises)
          .then(() => {
            ElMessage.success(`成功删除${this.multipleSelection.length}个景区`)
            this.fetchScenicList()
            this.multipleSelection = []
          })
          .catch(() => {
            ElMessage.error('批量删除失败')
          })
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    },

    // 多选处理
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 分页处理
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
    },

    handlePageChange(page) {
      this.currentPage = page
    },

    // 日期格式化
    formatDate(row, column, cellValue) {
      if (!cellValue) return ''
      const date = new Date(cellValue)
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const d = String(date.getDate()).padStart(2, '0')
      const h = String(date.getHours()).padStart(2, '0')
      const min = String(date.getMinutes()).padStart(2, '0')
      return `${y}-${m}-${d} ${h}:${min}`
    }
  },

  mounted() {
    this.fetchRegions().then(() => {
      this.fetchScenicList()
    })
  }
}
</script>

<style scoped>
.scenic-list-container {
  padding: 32px 0;
  background: #f7f8fa;
  min-height: 100vh;
}

.header-section {
  background: linear-gradient(135deg, #a0c4e4 0%, #7fa8d1 100%);
  padding: 20px 25px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(160, 196, 228, 0.2);
  margin-bottom: 24px;
  color: #2c3e50;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section .page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}

.title-section .page-title i {
  font-size: 28px;
  color: #2c3e50;
}

.title-section .page-subtitle {
  margin: 5px 0 0;
  font-size: 14px;
  color: #4a5568;
}

.total-count .count-card {
  background: rgba(255, 255, 255, 0.7);
  padding: 12px 20px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid #e2e8f0;
}

.count-label {
  font-size: 14px;
  margin-bottom: 5px;
  color: #4a5568;
}

.count-value {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
}

.query-card {
  margin-bottom: 18px;
  box-shadow: 0 2px 12px #f0f1f2;
  border-radius: 10px;
  background: #fff;
  padding: 16px;
}

.query-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.table-card {
  box-shadow: 0 2px 12px #f0f1f2;
  border-radius: 10px;
  background: #fff;
  padding: 16px 8px 8px 8px;
}

.data-table-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  margin-bottom: 20px;
}

:deep(.el-table) {
  border-radius: 12px 12px 0 0;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8fafc !important;
  font-weight: 600;
  color: #4a5568;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table__row:hover) {
  background-color: #f0f4f8;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 15px 0;
}

:deep(.el-pagination) .btn-prev,
:deep(.el-pagination) .btn-next {
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

:deep(.el-pagination) .el-pager li {
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  margin: 0 4px;
  background: white;
}

:deep(.el-pagination) .el-pager li.active {
  background: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
  color: white;
}

:deep(.el-pagination__jump) .el-input__inner {
  border-radius: 8px;
}

/* 按钮样式 */
.primary-btn {
  background: #409eff;
  color: #fff;
  border-radius: 6px;
  border: none;
  padding: 6px 18px;
  font-weight: 500;
  transition: all 0.2s;
}
.primary-btn:hover {
  background: #66b1ff;
  color: #fff;
}

.reset-btn {
  background: #f5f7fa;
  color: #409eff;
  border-radius: 6px;
  border: 1.5px solid #409eff;
  padding: 6px 18px;
  font-weight: 500;
  transition: all 0.2s;
}
.reset-btn:hover {
  background: #ecf5ff;
  color: #409eff;
  border-color: #409eff;
}

.add-btn {
  background: #fff;
  border: 1.5px solid #409eff;
  color: #409eff;
  border-radius: 6px;
  padding: 6px 18px;
  font-weight: 500;
  transition: all 0.2s;
}
.add-btn:hover {
  background: #ecf5ff;
  color: #409eff;
  border-color: #409eff;
}

.danger-btn {
  background: #fff;
  border: 1.5px solid #f56c6c;
  color: #f56c6c;
  border-radius: 6px;
  padding: 6px 18px;
  font-weight: 500;
  transition: all 0.2s;
}
.danger-btn:hover {
  background: #fef0f0;
  color: #f56c6c;
  border-color: #f56c6c;
}
</style>